import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  Modal,
  TextArea,
  List as MobileList,
  Toast,
  FloatingBubble,
  Tag,
  Dialog,
  Button,
  Input,
} from 'antd-mobile';
import { AddOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import { listDynamics, publishDynamic, readDynamic } from '../../server/api';

export default function MessageList() {
  const navigate = useNavigate();

  const [items, setItems] = useState([]);

  const [visible, setVisible] = useState(false);
  const [content, setContent] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const textAreaRef = useRef(null);

  useEffect(() => {
    if (visible) {
      // 弹窗打开后，自动聚焦输入框，提升“还原度”体验
      setTimeout(() => {
        textAreaRef.current?.focus?.();
      }, 0);
    }
  }, [visible]);

  useEffect(() => {
    (async () => {
      try {
        const res = await listDynamics({ page: 1, pageSize: 20 });
        const list = (res?.items || []).map((x) => ({
          id: String(x.id),
          content: x.content,
          read: x.readCount ?? 0,
          createdAt: x.createdAt ? Date.parse(x.createdAt) : Date.now(),
          imageUrl: x.imageUrl,
        }));
        setItems(list);
      } catch (e) {}
    })();
  }, []);

  const timeText = (ts) => {
    const diff = Math.floor((Date.now() - ts) / (24 * 3600 * 1000));
    if (diff <= 0) return '刚刚';
    return `${diff}天前`;
  };

  const listNodes = useMemo(
    () => (
      <MobileList style={{ background: 'transparent' }}>
        {items.map((item) => (
          <MobileList.Item
            key={item.id}
            onClick={async () => {
              try {
                await readDynamic({ id: Number(item.id) });
                setItems((prev) =>
                  prev.map((it) =>
                    it.id === item.id ? { ...it, read: (it.read || 0) + 1 } : it
                  )
                );
              } catch (e) {}
              navigate(`/message/${item.id}`);
            }}
            arrow={false}
            description={
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ color: '#999' }}>
                  {timeText(item.createdAt)}
                </span>
                <span style={{ marginLeft: 'auto', color: '#999' }}>
                  {item.read}人已读
                </span>
                <Tag
                  color="success"
                  onClick={(e) => {
                    e.stopPropagation();
                    Toast.show('已分享');
                  }}
                >
                  分享
                </Tag>
                <Tag
                  color="danger"
                  onClick={(e) => {
                    e.stopPropagation();
                    (async () => {
                      const confirm = await Dialog.confirm({
                        content: '确认删除该消息？',
                      });
                      if (confirm) {
                        setItems((prev) =>
                          prev.filter((x) => x.id !== item.id)
                        );
                        Toast.show({ content: '已删除' });
                      }
                    })();
                  }}
                >
                  删除
                </Tag>
              </div>
            }
          >
            <div style={{ fontSize: 16 }}>{item.content}</div>
          </MobileList.Item>
        ))}
      </MobileList>
    ),
    [items, navigate]
  );

  const handlePublish = async () => {
    const text = content.trim();
    if (!text) {
      Toast.show({ content: '请输入消息内容' });
      return;
    }
    const img = imageUrl.trim();
    if (!img) {
      Toast.show({ content: '请输入图片地址' });
      return;
    }
    try {
      await publishDynamic({ userId: 1, content: text, imageUrl: img });
      const res = await listDynamics({ page: 1, pageSize: 20 });
      const list = (res?.items || []).map((x) => ({
        id: String(x.id),
        content: x.content,
        read: x.readCount ?? 0,
        createdAt: x.createdAt ? Date.parse(x.createdAt) : Date.now(),
        imageUrl: x.imageUrl,
      }));
      setItems(list);
      textAreaRef.current?.blur?.();
      setContent('');
      setImageUrl('');
      setVisible(false);
      Toast.show({ icon: 'success', content: '已发布' });
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (e) {}
  };

  return (
    <div style={{ padding: 16 }}>
      <div
        style={{
          height: 44,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#00b578',
          color: '#fff',
          borderRadius: 8,
          marginBottom: 12,
        }}
      >
        发条消息
      </div>

      {listNodes}

      {/* 右下角固定操作区 */}
      <div
        style={{
          position: 'fixed',
          right: 24,
          bottom: 120, // 整体上移
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center', // 水平居中对齐
          zIndex: 100,
        }}
      >
        {/* 申请退款和举报投诉按钮容器 */}
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'flex-end',
            gap: 12,
            marginBottom: 16,
          }}
        >
          <Button
            style={{
              backgroundColor: '#16C05D',
              border: 'none',
              color: '#fff',
              borderRadius: 22,
              padding: '8px 16px',
              boxShadow: '0 4px 12px rgba(22, 192, 93, 0.3)',
            }}
            onClick={() => navigate('/refund')}
          >
            申请退款
          </Button>
          <Button
            style={{
              backgroundColor: '#16C05D',
              border: 'none',
              color: '#fff',
              borderRadius: 22,
              padding: '8px 16px',
              boxShadow: '0 4px 12px rgba(22, 192, 93, 0.3)',
            }}
            onClick={() => navigate('/complaint')}
          >
            举报投诉
          </Button>
        </div>

        {/* 恢复原生的 FloatingBubble 作为加号按钮 */}
        <FloatingBubble
          axis="xy"
          magnetic="x"
          style={{
            '--initial-position-bottom': '80px',
            '--initial-position-right': '20px',
            '--background': '#16C05D',
            '--color': 'white',
          }}
          onClick={() => setVisible(true)}
        >
          <AddOutline fontSize={24} />
        </FloatingBubble>
      </div>

      <Modal
        visible={visible}
        title="发布消息"
        content={
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <TextArea
              placeholder="输入消息内容..."
              value={content}
              onChange={setContent}
              rows={4}
              ref={textAreaRef}
            />
            <Input
              placeholder="输入图片地址..."
              value={imageUrl}
              onChange={setImageUrl}
            />
          </div>
        }
        closeOnAction
        showCloseButton
        actions={[
          { key: 'cancel', text: '取消', onClick: () => setVisible(false) },
          { key: 'ok', text: '发布', bold: true, onClick: handlePublish },
        ]}
        onClose={() => setVisible(false)}
      />
    </div>
  );
}
